﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.Xml;
using System.Xml.XPath;
using BrowserGameFramework.Common.Configuration;
using BrowserGameFramework.Common.Logging;
using BrowserGameFramework.Common.Exceptions;
using BrowserGameFramework.Common.XmlHelper;

namespace BrowserGameFramework.Mail
{
    public static class MailHandler
    {
        /// <summary>
        /// Sends an email to a list of user.
        /// </summary>
        /// <param name="address">Collection of MailAddress</param>
        /// <param name="subject">The subject text</param>
        /// <param name="message">the message text (could contain htlm)</param>
        public static void SendMail(MailAddressCollection address, string subject, string message)
        {
            try
            {
                Trace.TraceEnterEvent("SendMail");

                if (address == null || address.Count == 0)
                {
                    throw new BGFBackendException("No valid emailaddress given");
                }

                MailServerConfig config = MailServerConfig.GetAppConf();


                SmtpClient client = new SmtpClient(config.Host, config.Port);

                client.EnableSsl = config.UseSSL;

                NetworkCredential credentials = new System.Net.NetworkCredential(config.User, config.Pass);
                client.Credentials = credentials;

                MailMessage msg = new MailMessage();


                foreach (MailAddress ad in address)
                {
                    msg.To.Add(ad);
                }

                MailAddress from = new MailAddress(config.ReplyMail);

                msg.Subject = subject;
                msg.Sender = from;
                msg.Priority = MailPriority.Normal;
                msg.IsBodyHtml = true;
                msg.Body = message;

                msg.From = from;

                client.Send(msg);

                Trace.TraceLeaveEvent("SendMail");
            }
            catch (Exception ex)
            {
                Trace.TraceExceptionError("Error while mailing", ex);
            }
        }

        /// <summary>
        /// Sends a html mail
        /// </summary>
        /// <param name="address">Mail address collection</param>
        /// <param name="subject">The mail subject</param>
        /// <param name="message">The message</param>
        public static void SendHtmlMail(MailAddressCollection address, string subject, XPathDocument message)
        {
            try
            {
                Trace.TraceEnterEvent("SendMail");

                if (address == null || address.Count == 0)
                {
                    throw new BGFBackendException("No valid emailaddress given");
                }

                MailServerConfig config = MailServerConfig.GetAppConf();

                SmtpClient client = new SmtpClient(config.Host, config.Port);

                client.EnableSsl = config.UseSSL;

                NetworkCredential credentials = new NetworkCredential(config.User, config.Pass);
                client.Credentials = credentials;

                MailMessage msg = new MailMessage();

                AlternateView htmlView =
                AlternateView.CreateAlternateViewFromString(message.CreateNavigator().OuterXml,
                    Encoding.UTF8,
                    "text/html");


                foreach (MailAddress ad in address)
                {
                    msg.To.Add(ad);
                }

                MailAddress from = new MailAddress(config.ReplyMail);

                msg.Subject = subject;
                msg.Sender = from;
                msg.Priority = MailPriority.Normal;
                msg.IsBodyHtml = true;
                msg.AlternateViews.Add(htmlView);

                msg.From = from;

                client.Send(msg);

                Trace.TraceLeaveEvent("SendMail");
            }
            catch (Exception ex)
            {
                Trace.TraceExceptionError("Error while mailing", ex);
            }
        }

        /// <summary>
        /// Sends a registration mail to the target
        /// </summary>
        /// <param name="target">Email address of registrated user</param>
        public static void SendRegistrationMail(string target, Uri activationLink)
        {
            MailAddress address = new MailAddress(target);
            MailAddressCollection collection = new MailAddressCollection();
            collection.Add(address);

            SendMail(collection, "Your registration", "Thank you for your registration" + activationLink.ToString());
        }

        public static string GenerateTemplateMail(XPathDocument xDoc)
        {
            XPathNavigator navi = xDoc.CreateNavigator();
            string templatePath = AppConfMan.GetKeyAsString("RegistrationMailTemplate");
            XPathDocument xpathXsl = new XPathDocument(@templatePath);
            string errorMsg = string.Empty;

            XPathDocument resDoc = XmlHelper.TransformCompiled(xDoc, xpathXsl, out errorMsg);

            return resDoc.CreateNavigator().OuterXml;
        }

    }
}
